import {app,BrowserWindow,Menu,ipcMain,shell, globalShortcut } from "electron"
import path from 'path'
let win:BrowserWindow | null
import {spawn, exec} from 'child_process'
import fs from 'fs'
let server:any = null
let logWindow: BrowserWindow | null = null;
const logCache: string[] = [];
const MAX_LOG_COUNT = 1000;
const BATCH_SIZE = 10;

// 窗口控制相关的IPC处理
ipcMain.handle('minimize-window', () => {
    if (win) {
        win.minimize()
    }
})

ipcMain.handle('toggle-maximize', () => {
    if (win) {
        if (win.isMaximized()) {
            win.unmaximize()
            return false
        } else {
            win.maximize()
            return true
        }
    }
    return false
})

ipcMain.handle('close-window', () => {
    if (win) {
        win.close()
    }
})

ipcMain.on("openDialog",(event,arg) => {
    let path:string = arg // 要打开系统的对话框路径
    shell.openPath(path)
})

app.disableHardwareAcceleration() // 禁用硬件加速

const startServer = function() {
    if (process.env["NODE_ENV"] === "development") {
        // 开发环境：在指定目录运行 npm run dev
        const EXECUTION_OPTIONS = {
            windowsHide: true,
            detached: false,
            cwd: 'C:\\Users\\aiyan\\Desktop\\wired_system\\apps\\backend', // 设置工作目录
            shell: true
        };
        server = spawn('npm', ['run', 'dev'], EXECUTION_OPTIONS);
    } else {
        // 生产环境：运行可执行文件
        let currentPath:string = path.join(process.cwd(),"catl_server.exe");
        const EXECUTION_OPTIONS = {
            windowsHide: true,
            detached: false, // 让子进程独立于父进程运行
        };
        server = spawn(currentPath,[],EXECUTION_OPTIONS);
    }

     // 监听这个服务输出
     server.stdout.on('data', (data: any) => {
        const log = data.toString();
        console.log(log);
        logCache.push(log);
        if (logCache.length > MAX_LOG_COUNT) {
            logCache.shift(); // 移除最早的日志
        }
        if (logCache.length % BATCH_SIZE === 0) {
            win?.webContents.send('log-data', logCache);
        }
     });

     // 监听服务关闭
     server.stderr.on('data', (err: any) => {
        const errorLog = err.toString();
        console.error(errorLog);
        logCache.push(errorLog);
        if (logCache.length > MAX_LOG_COUNT) {
            logCache.shift();
        }
        if (logCache.length % BATCH_SIZE === 0) {
            logWindow?.webContents.send('log-data', logCache);
        }
     });
}

Menu.setApplicationMenu(null) // 取消菜单项
const createBrowserWindow = () => {
    win = new BrowserWindow({
        title: "美镓传感", // 设置窗口标题
        frame: false, // 禁用默认标题栏
        titleBarStyle: 'hidden', // 隐藏标题栏
        webPreferences: {
            preload: path.join(__dirname,"preload.js"),
            nodeIntegration: false,
            contextIsolation: true
        },
        // icon: path.join(__dirname, "../src/assets/logo.png") // 设置应用图标
    })
    if (process.env["NODE_ENV"] !=="development") {
            win.loadFile(path.join(__dirname,"../index.html"))
    } else {
        win.loadURL(`http://${process.env["VITE_DEV_SERVER_HOST"]}`+ `:${process.env["VITE_DEV_SERVER_PORT"]}`)
    }
}
    app.on("ready",() => {
        startServer()
        setTimeout(() => {
            createBrowserWindow()
        }, 500);
    })

    // 监测渲染进程的关闭
    app.on("render-process-gone", function (event, webContents, details) {
        // 基于我在开发的程序本身的设定，此处重启应用就可以了
        win?.reload()
    });

// 关闭页面，服务停止操作
app.on("window-all-closed",() => {
    if (process.platform !== 'darwin') {
        app.quit()
        if (server) {
            if (process.platform === 'win32' && process.env["NODE_ENV"] === "development") {
                // Windows 下使用 taskkill 强制终止进程树
                exec(`taskkill /pid ${server.pid} /T /F`, (error) => {
                    if (error) {
                        console.log('进程终止可能失败:', error.message);
                    }
                });
            } else {
                server.kill()
            }
        }
    }
})



